#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define MAX_LINE 256
#define FILE_NAME "data.txt"
void my_set_key(const char *key, const char *value);
// 函数声明
void set_key_value(const char *key, const char *value);
char *get_value(const char *key);
void remove_key(const char *key);

int main() {

	my_set_key("1", "11111");
	my_set_key("2", "22222");
	my_set_key("3", "33333");
	my_set_key("4", "44444");
	// 示例：获取键值对
//	char *value = get_value("password");
//	if (value) {
//		printf("password: %s\n", value);
//		free(value); // 记得释放内存
//	} else {
//		printf("Key not found.\n");
//	}
//	
//	// 示例：删除键值对
//	remove_key("email");
	
	return 0;
}
void my_set_key(const char *key, const char *value)
{
	FILE *file = fopen("new_data.txt", "r");
	FILE *temp_file = fopen("temp.txt", "w");
	if(!file){
		printf("文件打开失败，新建文件...\n");
		FILE *t = fopen("new_data.txt", "w");
		fclose(t);
	}
	bool found = false;
	char line[MAX_LINE];
	int count = 0;
//	while (fgets(line, sizeof(line), file)) {
//		
//		
//	}
	while (fgets(line, sizeof(line), file)) {
		char current_key[MAX_LINE];
		sscanf(line, "%[^=]", current_key);
		if (strcmp(current_key, key) == 0) {
//			printf("替换新值\n");
			fprintf(temp_file, "%s=%s\n", key, value); // 替换值
			found = 1;
		} else {
//			printf("不需要替换\n");
			fputs(line, temp_file); // 保留原始行
		}
		printf("%d\n",count++);
	}
	if(!found){
		//TODO
		fprintf(temp_file, "%s=%s\n", key, value); // 添加新键值对
	}
	fclose(file);
	fclose(temp_file);
	remove("new_data.txt");
	rename("temp.txt", "new_data.txt");
}

// 获取键对应的值
char *get_value(const char *key) {
	FILE *file = fopen(FILE_NAME, "r");
	char line[MAX_LINE];
	char current_key[MAX_LINE], *value = NULL;
	
	if (!file) {
		perror("File error");
		return NULL;
	}
	
	while (fgets(line, sizeof(line), file)) {
		sscanf(line, "%[^=]=%[^\n]", current_key, line);
		
		if (strcmp(current_key, key) == 0) {
			value = strdup(line); // 复制值到内存
			break;
		}
	}
	
	fclose(file);
	return value;
}

// 删除键值对
void remove_key(const char *key) {
	FILE *file = fopen(FILE_NAME, "r");
	FILE *temp_file = fopen("temp.txt", "w");
	char line[MAX_LINE];
	
	if (!file || !temp_file) {
		perror("File error");
		exit(EXIT_FAILURE);
	}
	
	// 将所有非目标键的行写入临时文件
	while (fgets(line, sizeof(line), file)) {
		char current_key[MAX_LINE];
		sscanf(line, "%[^=]", current_key);
		
		if (strcmp(current_key, key) != 0) {
			fputs(line, temp_file);
		}
	}
	
	fclose(file);
	fclose(temp_file);
	remove(FILE_NAME);
	rename("temp.txt", FILE_NAME);
}

